import { nextTick, ref, watch } from 'vue'
import { isEmpty } from '@/utils/util'

export default function useTableSelection(tableData, tableRef, change, idKey = 'id') {
  const multipleSelection = ref([])

  const handleSelectChange = (selection, row) => {
    const selected = selection.length && selection.indexOf(row) !== -1
    if (selected) {
      multipleSelection.value.push(row)
    } else {
      const selectIndex = multipleSelection.value.findIndex((item) => item[idKey] === row[idKey])
      multipleSelection.value.splice(selectIndex, 1)
    }
    onChange()
  }

  const handleSelectAll = (selection) => {
    if (selection.length > 0) {
      // 只添加当前页中尚未选中的项
      const newSelections = selection.filter(
        (item) => !multipleSelection.value.some((selected) => selected[idKey] === item[idKey]),
      )
      multipleSelection.value.push(...newSelections)
    } else {
      // 取消选择当前页的所有项
      multipleSelection.value = multipleSelection.value.filter((item) =>
        tableData.value.every((it) => it[idKey] != item[idKey]),
      )
    }
    onChange()
  }

  // 设置更改表格当前选中项
  const setTableSelection = () => {
    let ref = tableRef.value
    if (ref && 'tableRef' in ref) {
      ref = ref.tableRef
    }
    if (!ref || !ref.data) {
      return
    }
    ref.data.forEach((data) => {
      const selected = multipleSelection.value.some((item) => data[idKey] === item[idKey])
      ref.toggleRowSelection(data, selected)
    })
  }

  const clearSelection = () => {
    if (isEmpty(multipleSelection.value)) {
      return
    }
    multipleSelection.value = []
    setTableSelection()
    onChange()
  }

  watch(
    () => tableData.value,
    () => {
      nextTick(() => {
        setTableSelection()
      })
    },
  )

  const onChange = () => {
    change?.(multipleSelection.value)
  }

  return {
    handleSelectChange,
    handleSelectAll,
    multipleSelection,
    clearSelection,
  }
}
